package com.zhilehuo.pretask.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.zhilehuo.pretask.databinding.ItemDifficultyBinding

/**
 * @Description: 难度适配器
 * @Author: Realnt
 * @Date:
 */
class DifficultyAdapter(
    private val onClick: (Int) -> Unit
) : ListAdapter<Int, DifficultyAdapter.ViewHolder>(DiffCallback) {

    private var currentDifficulty: Int? = null
    private var previousDifficulty: Int? = null

    inner class ViewHolder(val binding: ItemDifficultyBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(difficulty: Int) {
            binding.apply {
                difficultyText.text = String.format("%s", difficulty)
                root.setOnClickListener {
                    // 先记录前一个选中项
                    previousDifficulty = currentDifficulty
                    // 更新当前选中项
                    currentDifficulty = difficulty
                    // 通知外部
                    onClick(difficulty)
                    notifyDataSetChanged()
                }

                if (difficultyText.text.equals(currentDifficulty.toString())){ difficultyText.strokeWidth = 2 }
                else { difficultyText.strokeWidth = 0 }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        ViewHolder(ItemDifficultyBinding.inflate(LayoutInflater.from(parent.context), parent, false))

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
        if (holder.binding.difficultyText.text.equals(currentDifficulty.toString())){ holder.binding.difficultyText.strokeWidth = 2 }
        else { holder.binding.difficultyText.strokeWidth = 0 }
    }

    object DiffCallback : DiffUtil.ItemCallback<Int>() {
        override fun areItemsTheSame(oldItem: Int, newItem: Int) = oldItem == newItem
        override fun areContentsTheSame(oldItem: Int, newItem: Int) = oldItem == newItem
    }

    fun setCurrentDifficulty(difficulty: Int) {
        // 外部更新时也记录前一个状态
        previousDifficulty = currentDifficulty
        currentDifficulty = difficulty
        refreshBothItems()
    }

    /**
     * @Description: 精准刷新方法
     * @Param  :
     * @Return  :
     */
    private fun refreshBothItems() {
        previousDifficulty?.let { old ->
            val previousPosition = currentList.indexOf(old)
            if (previousPosition != -1) {
                notifyItemChanged(previousPosition)
            }
        }

        currentDifficulty?.let { new ->
            val newPosition = currentList.indexOf(new)
            if (newPosition != -1) {
                notifyItemChanged(newPosition)
            }
        }
    }
}